﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.OracleClient;
using picFilter.App_Code;
using System.Data;
using System.Web;
using System.Text;

namespace picFilter.Controllers
{
    public class picsController : ApiController
    {
        // GET api/pics
        /// <summary>
        /// 获取所有相片
        /// </summary>
        /// <returns></returns>
        public object Get()
        {
            try
            {
                OracleParameter picId = DBHelper.createParameter("picId", OracleType.Int32, 1);
                DataTable dt = DBHelper.ExecuteDataTable("select * From pic Where id=:picId", picId);
                return dt;
            }
            catch (Exception ex)
            {
                return new { error = "获取相片失败！", syserror = ex.Message };
            }
        }

        // GET api/pics/5
        /// <summary>
        /// 获取指定相片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object Get(int id)
        {
            try
            {
                OracleParameter picId = DBHelper.createParameter("picId", OracleType.Int32, id);
                DataTable dt = DBHelper.ExecuteDataTable("select * From pic Where id=:picId", picId);
                return dt;
            }
            catch (Exception ex)
            {
                return new { error = "获取相片失败！", syserror = ex.Message };
            }
        }

        // POST api/pics
        /// <summary>
        /// 保存上传的图片到数据库,返回上传的记录
        /// </summary>
        /// <returns>[{rows}]</returns>
        public object Post()
        {
            try
            {
                if (Request.Content.IsMimeMultipartContent())
                {
                    HttpFileCollection files = HttpContext.Current.Request.Files;
                    if (files.Count > 0)
                    {                        
                        /*
                        int fileLength = files[0].ContentLength;
                        byte[] fileByte = new byte[fileLength];
                        files[0].InputStream.Read(fileByte, 0, fileLength);
                        string newFullName = Guid.NewGuid().ToString();
                        string origFullName = files[0].FileName;
                        string fileOrigName = files[0].FileName.LastIndexOf(".") > 0 ? origFullName.Substring(0, files[0].FileName.LastIndexOf(".")) : origFullName;
                        OracleParameter fileName = DBHelper.createParameter("fileName", OracleType.VarChar, fileOrigName);
                        OracleParameter fileFullName = DBHelper.createParameter("fileFullName", OracleType.VarChar, newFullName);
                        OracleParameter origName = DBHelper.createParameter("origName", OracleType.VarChar, origFullName);
                        OracleParameter fileData = DBHelper.createParameter("fileData", OracleType.Blob, fileByte);

                        var iResult = DBHelper.ExecuteNonQuery("insert Into Pic(id,fileName,fileFullName,origName,fileData) "
                            + "values(pic_seq.nextval,:fileName,:fileFullName,:origName,:fileData)", fileName, fileFullName, origName, fileData);

                        if (iResult > 0)
                        {
                            fileFullName = DBHelper.createParameter("fileFullName", OracleType.VarChar, newFullName);
                            DataTable dt = DBHelper.ExecuteDataTable("Select id,fileName,fileFullName,origName From pic"
                                + " Where fileFullName=:fileFullName", fileFullName);
                            return dt;
                        }
                        else
                        {
                            return new { error = "上传图片失败！" };
                        }*/
                        
                        //List<OracleParameter> paramList=new List<OracleParameter>();
                        
                        //sbCmdText.Append("Declare Begin ");


                        List<object> outPic = new List<object>();

                        for (int i = 0; i < files.Count; i++)
                        {
                            StringBuilder sbCmdText = new StringBuilder();
                            HttpPostedFile currFile = files[i];
                            int fileLength = currFile.ContentLength;
                            byte[] fileByte = new byte[fileLength];
                            currFile.InputStream.Read(fileByte, 0, fileLength);
                            string newFullName = Guid.NewGuid().ToString();
                            string origFullName = currFile.FileName;
                            string fileOrigName = currFile.FileName.LastIndexOf(".") > 0 ? origFullName.Substring(0, currFile.FileName.LastIndexOf(".")) : origFullName;

                            OracleParameter fileName = DBHelper.createParameter("fileName", OracleType.VarChar,500, fileOrigName);
                            OracleParameter fileFullName = DBHelper.createParameter("fileFullName", OracleType.VarChar, newFullName);
                            OracleParameter origName = DBHelper.createParameter("origName", OracleType.VarChar, origFullName);
                            OracleParameter fileData = DBHelper.createParameter("fileData", OracleType.Blob, fileByte);
                            OracleParameter outId = DBHelper.createParameter("outId", OracleType.Number, ParameterDirection.InputOutput);
                            OracleParameter outFileName = DBHelper.createParameter("outFileName", OracleType.VarChar, 500, ParameterDirection.InputOutput);
                            
                            sbCmdText.Append("insert Into Pic(id,fileName,fileFullName,origName,fileData) ");
                            sbCmdText.Append("values(pic_seq.nextval,:fileName,:fileFullName,:origName,:fileData) ");
                            sbCmdText.Append("returning id,fileName into :outId,:outFileName ");

                            DBHelper.ExecuteNonQuery(sbCmdText.ToString(), fileName, fileFullName, origName, fileData, outId, outFileName);
                            outPic.Add(new { id = Int32.Parse(outId.Value.ToString()), fileName = outFileName.Value.ToString() });

                        }
                        
                        //OracleParameter[] parameters = paramList.ToArray();                                               
                        //return sbCmdText.ToString();
                        return outPic;
                         
                    }
                    else
                    {                        
                        return new { error = "请选择正确的文件！" };
                    }
                }
                else
                {
                    return new { error = "请先选择文件！" };
                }
            }
            catch(Exception ex)
            {
                return new { error = "上传图片失败！", syserror = ex.Message };
            }
        }

        // PUT api/pics/5
        public void Put(int id, [FromBody]string value)
        {

        }

        // DELETE api/pics/5
        /// <summary>
        /// 删除指定相片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object Delete(int id)
        {
            try
            {
                OracleParameter picId = DBHelper.createParameter("picId", OracleType.Int32, id);
                DBHelper.ExecuteNonQuery("Delete From pic Where id=:picId", picId);
                return new { success = "OK" };
            }
            catch(Exception ex)
            {
                return new { error = "删除失败！", syserror = ex.Message };
            }
        }
    }
}
